package com.xiang.action.impl;

import com.xiang.doman.Good;
import com.xiang.mapper.GoodMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.xiang.action.GoodAction;

@Slf4j
@Component
public class GoodActionImpl implements GoodAction {

    @Autowired
    GoodMapper goodMapper;

    @Override
    public boolean tryGood(BusinessActionContext actionContext, int goodId, int num) {
        Good good=goodMapper.selectById(goodId);
        if(good.getGoodStock()<num){
            throw new RuntimeException("库存不足！");
        }
        /**
         * todo 【幂等性、空回滚 、悬挂问题（框架已解决：@TwoPhaseBusinessAction注解配置）】
         * 相关: https://seata.apache.org/zh-cn/blog/seata-tcc-fence/#4-tcc-%E5%AD%98%E5%9C%A8%E9%97%AE%E9%A2%98
         */

        log.info("good 执行 try方法。。。");
        goodMapper.reduceStock(goodId,num);

        return true;
    }

    @Override
    public boolean commit(BusinessActionContext actionContext) {
        log.info("good 执行 commit方法。。。");
        int goodId= actionContext.getActionContext("goodId",Integer.class).intValue();
        int num= actionContext.getActionContext("num",Integer.class).intValue();
        goodMapper.commitStock(goodId,num);

        return true;
    }

    @Override
    public boolean rollback(BusinessActionContext actionContext) {
        log.info("good 执行 rollback方法。。。");
        int goodId= actionContext.getActionContext("goodId",Integer.class).intValue();
        int num= actionContext.getActionContext("num",Integer.class).intValue();
        goodMapper.cancleStock(goodId,num);

        return true;
    }
}
